package Serveur;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.StringTokenizer;


public class Connexion  extends Thread{
	/**
	 * inputs et outputs
	 */
	private Socket sock1;
	private int numConn;
	private BufferedReader in;
	private DataOutputStream out;
	private String  page,requeteGen;
	
	public void run(){
		try {
			in = new BufferedReader ( new InputStreamReader(sock1.getInputStream()));			
			out = new DataOutputStream (sock1.getOutputStream());
			//Canaux OK
			lecture();
			sock1.close();	
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public Connexion(Socket soc, int NumConnexion){
		sock1 = soc;
		numConn=NumConnexion;	
	}
	
	public void lecture()throws IOException{
		String requete= in.readLine();

		if ( requete.startsWith("GET")){
			//Si c'est un GET
			if (recuperationFichier(requete))
				out.writeBytes(creationEntete(200)+"\r\n"+page);
			else{
			
				out.writeBytes(creationEntete(404));
			}
		}else if ( requete.startsWith("HEAD")){
			//Si c'est un HEAD
			out.writeBytes(creationEntete(200));
		}else if (requete.startsWith("POST")){
			//Si c'est un POST
			
		}else {
			//Sinon
			out.writeBytes(creationEntete(501));
			}
			
		
		
	}
	
	private boolean recuperationFichier(String req){
		
		File fichier = new File("/home/www/"+extractionUrl(req));
		FileInputStream fis;
		BufferedReader br;
		String tmp;
		StringBuffer sb = new StringBuffer();
		try {
			fis= new  FileInputStream(fichier);
			br= new BufferedReader(new InputStreamReader(fis));
			tmp=br.readLine();
			while(tmp!=null){
				sb.append(tmp+"\n");
				tmp= br.readLine();
			}
			page=sb.toString();
			br.close();
		} catch (IOException e) {	
			return false;
		}
			
		return true;
	}
	
	private String creationEntete(int val){
		StringBuffer entete = new StringBuffer();
		entete.append("HTTP/1.0 ");
		//codes connus
	    switch (val) {
	      case 200:
	    	  entete.append("200 OK");
	        break;
	      case 400:
	    	  entete.append("400 Bad Request");
	        break;
	      case 403:
	    	  entete.append("403 Forbidden");
	        break;
	      case 404:
	    	  entete.append("404 Not Found");
	        break;
	      case 500:
	    	  entete.append("500 Internal Server Error");
	        break;
	      case 501:
	    	  entete.append("501 Not Implemented");
	        break;
	    }
	  
	    	
	    //entete.append("\n"); 
	    
	    entete.append("\r\nContent-Type:");
	    if(requeteGen.endsWith(".html")||requeteGen.endsWith(".htm")){
	    	entete.append("text/html");
	    }else if (requeteGen.endsWith(".gif")){
	    	entete.append("image/gif");
	    }else if (requeteGen.endsWith(".jpg")||requeteGen.endsWith(".jpeg")){
	    	entete.append("image/jpeg");
	    }else
	    	entete.append("text/plain");
	    
	    entete.append("\r\nConnection: close\r\n"); //we can't handle persistent connections
	    entete.append("Server: Rie07JavaWebServer\r\n"); //server name
	    return entete.toString();
	}
	
	private String extractionUrl(String get){
		//GET /index2.html HTTP/1.1\r\n
		String tmp;
		StringTokenizer st = new StringTokenizer(get);
		st.nextToken(); //passage du GET
		tmp=st.nextToken();	
		if (tmp.compareTo("/")==0){
			tmp="index.html";
		}
		requeteGen=tmp;
		return tmp;
	}
	
	private String getTime(){
	Calendar calendar = Calendar.getInstance();
	SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",Locale.US);
	    		    
	    return ("Date: " +dateFormat.format(calendar.getTime()));
	}

}
